import json
import re
import os

import pandas as pd
import requests
import time

from sparkai.llm.llm import ChatSparkLLM, ChunkPrintHandler
from sparkai.core.messages import ChatMessage
#星火认知大模型Spark Max的URL值，其他版本大模型URL值请前往文档（https://www.xfyun.cn/doc/spark/Web.html）查看
SPARKAI_URL = 'wss://spark-api.xf-yun.com/v3.5/chat'
#星火认知大模型调用秘钥信息，请前往讯飞开放平台控制台（https://console.xfyun.cn/services/bm35）查看
SPARKAI_APP_ID = '8dbb4b5e'
SPARKAI_API_SECRET = 'NzZiZDUwMmFmYzIwZTRiMjVhNzQ0NjNk'
SPARKAI_API_KEY = 'e51a7fb80f7a69d365dcecb6b9a01dc6'
#星火认知大模型Spark Max的domain值，其他版本大模型domain值请前往文档（https://www.xfyun.cn/doc/spark/Web.html）查看
SPARKAI_DOMAIN = 'generalv3.5'


# headers = {
#     'appkey': 'k4kltkgguzgajqruam6dnovtpmhy1a7r7lfhe36ic',
#     'udid': 'kg',
#     'vendor': 'azure',
#     # 'timestamp': '1678699208',
#     'User-Agent': 'apifox/1.0.0 (https://www.apifox.cn)',
#     'Content-Type': 'application/json'
# }
# url = "https://unigpt-api.uat.hivoice.cn/rest/v1/chat/completions"


# def post_gpt(text):
#     headers['timestamp'] = str('%d123' % int(time.time()))
#     body_info = json.dumps({"messages": [{"content": text}], "model": "azure-gpt4-8k"})
#     results = requests.post(url, headers=headers, data=body_info)
#     gpt_result = json.loads(results.text)

#     print(gpt_result)
#     if "result" not in gpt_result or "choices" not in gpt_result["result"]:
#         results = requests.post(url, headers=headers, data=body_info)
#         gpt_result = json.loads(results.text)
#     # print(gpt_result)
#     return gpt_result["result"]["choices"][0]["message"]["content"]
def post_spark(text):
    spark = ChatSparkLLM(
        spark_api_url=SPARKAI_URL,
        spark_app_id=SPARKAI_APP_ID,
        spark_api_key=SPARKAI_API_KEY,
        spark_api_secret=SPARKAI_API_SECRET,
        spark_llm_domain=SPARKAI_DOMAIN,
        streaming=False,
    )
    messages = [ChatMessage(
        role="user",
        content=text
    )]
    handler = ChunkPrintHandler()
    result = spark.generate([messages], callbacks=[handler])
    # print(result)
    input_str = str(result).split('\'')
    print(input_str[1])
    return input_str[1]

def data_expand():
    sheet_names = ["电台"]
    default_prompt = "当前为车机场景，以上为在车机场景下的一些用户说法示例， 请充分理解上述示例，并生成30条意图一样的说法，生成的说法需要符合人类口语习惯。"
    sheet_dict = pd.read_excel(excel_path, sheet_name=sheet_names, engine="openpyxl")

    def get_text(sample):
        return sample.split('\\t')[0]
    # col_index = 2
    for sheet_name, df in sheet_dict.items():
        last_intent_code = None
        for info in df.values:
            intent_code = info[0]
            intent_code = str(intent_code).replace('\n', '_').replace('）', '')
            if len(intent_code) == 0 or 'nan' in str(intent_code):
                intent_code = last_intent_code
            last_intent_code = intent_code
            writer = open(fr'{output_dir}\{intent_code.replace("/", "_")}.txt', encoding='utf-8', mode='a')
            # samples = '\n'.join(
            #     [f'示例{i}:{get_text(example)}' for i, example in enumerate(str(info[1]).split('\n')) if len(example) > 0])
            
            # 将 info[1] 转换为字符串并按换行符分割成列表
            lines = str(info[1]).split('\n')
            # 初始化一个空列表来存储处理后的示例文本
            formatted_samples = []
            # 遍历每一行及其索引
            for index, line in enumerate(lines):
                # 只处理非空行
                if len(line) > 0:
                    # 使用 f-string 格式化字符串，添加前缀 '示例<行号>:'
                    formatted_sample = f'示例{index}:{get_text(line)}'
                    # 将格式化后的字符串添加到列表中
                    formatted_samples.append(formatted_sample)

            # 将所有格式化后的字符串用换行符连接成一个多行字符串
            samples = '\n'.join(formatted_samples)
            # print(samples)
            constomized_prompt = info[2]

            if 'nan' != str(constomized_prompt) and len(constomized_prompt) > 0:
                input_text = f'{samples}\n{constomized_prompt}'
            else:
                input_text = f'{samples}\n{default_prompt}'
            # print(input_text)
            # result = post_gpt(input_text)
            result = post_spark(input_text)
            results = result.split('\\n')
            # result.extend(str(info[1]).split('\n'))
            # data_pre_label(result, writer)
            for result in results:
                writer.write(f'{result}\n')

            # intent_str = info[col_index + 3]
            # for new_sample in result:
            #     # writer.write(f'{new_sample}\t{intent_str}\n')
            #     writer.write(f'{new_sample}')


def data_pre_label(samples, writer_fp):
    examples = []
    waiting_label = []
    i = 1
    for sample in samples:
        sample_ele = sample.split('\\t')
        if len(sample_ele) > 1 and len(sample_ele[1]) > 0:
            examples.append(f'示例{i}{sample_ele[0]}\t{sample_ele[1]}')
            i += 1
        else:
            lines = sample.split('\\n')
            for line in lines:
                waiting_label.append(line)

    exampls_str = "\n".join(examples)
    # print("exampls_str:" + exampls_str)
    waiting_label_str = '\n'.join(waiting_label)
    # print("waiting_label_str:" + waiting_label_str)
    default_prompt = "上述示例中包含一个自然语言文本和对应的结构化信息，请充分理解上述示例，对下面的文本进行结构化信息标注，格式需要和示例中的一致。"

    model_input = f'{exampls_str}\n{default_prompt}{waiting_label_str}'
    print("model_input:"+model_input)
    result = post_spark(exampls_str)
    result = result.split('\n')
    result.extend(examples)

    for new_sample in result:
        new_sample = re.sub("^([0-9]+(\.|:)? ?)|(示例[0-9]+:? ?)", "", new_sample)
        # writer.write(f'{new_sample}\t{intent_str}\n')
        writer_fp.write(f'{new_sample}\n')


if __name__ == '__main__':
    excel_path = r"C:\Users\YZS\Desktop\LLM_generate\LLM_generate\sample_系统设置.xlsx"
    output_dir = r'C:\Users\YZS\Desktop\LLM_generate\LLM_generate\output\sys_setting'
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    data_expand()
